package com.zh.api.controller.common;


import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.zh.common.annotation.Log;
import com.zh.common.base.BaseController;
import com.zh.common.domain.MenuDO;
import com.zh.common.domain.Tree;
import com.zh.common.domain.UserDO;
import com.zh.common.plugins.shiro.TokeService;
import com.zh.common.plugins.shiro.utils.JWTUtil;
import com.zh.common.service.FileService;
import com.zh.common.service.MenuService;
import com.zh.common.service.UserService;
import com.zh.common.utils.MD5Utils;
import com.zh.common.utils.R;
import com.zh.common.utils.ResultEnum;
import com.zh.common.utils.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 运营系统登录模块
 */
@Controller
@Api("登录相关")
public class LoginController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	MenuService menuService;
	@Autowired
	FileService fileService;
	@Autowired
	UserService userService;
	@Autowired
	TokeService tokeService;

	@Autowired
	DefaultKaptcha producer;


	/**
	 * 前台接口传入json
	 * @param jsonParam
	 * @param response
	 * @return
	 */
	@Log("登录")
	@RequestMapping(value = "login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@ApiOperation("登录")
	public ResultVO ajaxLogin(@RequestBody JSONObject jsonParam, HttpServletResponse response) {

		String username=jsonParam.getString("username");
		String password=jsonParam.getString("password");
		int userType=Integer.parseInt(jsonParam.getString("userType"));
		System.out.println(jsonParam.toJSONString());
		UserDO vo = this.userService.getByUserName(username,userType);
		password = MD5Utils.encrypt(username, password);
		if (null != vo && vo.getPassword().equals(password)) {
			String tokenStr = JWTUtil.sign(username, vo.getPassword(),userType);
			//添加到redis中
			tokeService.addTokenToRedis(username,userType,tokenStr);
			Map<String,Object> resMap=new HashMap<>();
			resMap.put("tonken",tokenStr);
			List<Tree<MenuDO>> menus = menuService.getAllListMenuTree(vo.getUserId());
			resMap.put("menus",menus);
			response.setHeader("Authorization", tokenStr);
			return ResultVO.success(resMap);//缓存token
		} else {
			return ResultVO.error(ResultEnum.USER_PASSWORD_ERROR);
		}

	}


	@Log("获取菜单")
	@GetMapping({"/inex"})
	String getMenu(Model model) {
		/*List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
		model.addAttribute("menus", menus);
		model.addAttribute("name", getUser().getName());
		FileDO fileDO = fileService.get(getUser().getPicId());
		if (fileDO != null && fileDO.getUrl() != null) {
			if (fileService.isExist(fileDO.getUrl())) {
				model.addAttribute("picUrl", fileDO.getUrl());
			} else {
				model.addAttribute("picUrl", "/img/photo_s.jpg");
			}
		} else {
			model.addAttribute("picUrl", "/img/photo_s.jpg");
		}
		model.addAttribute("username", getUser().getUsername());
		return "index_v1";*/
		return null;
	}


	@PostMapping("/test")
	@ResponseBody
	@RequiresPermissions("sys:user:add")
	public R test(){
		System.out.print("------------->"+getUserId());
    return R.ok();
	}

	/**
	 * 生成验证码
	 */
	/**
	 * 生成验证码
	 *
	 * @return
	 */
	@GetMapping("/captcha")
	@ResponseBody
	@ApiOperation("获取验证码")
	public ResultVO captcha() throws IOException {
		try {
			// 生成文字验证码
			String text = producer.createText();
			// 生成图片验证码
			ByteArrayOutputStream outputStream = null;
			BufferedImage image = producer.createImage(text);
			outputStream = new ByteArrayOutputStream();
			ImageIO.write(image, "jpg", outputStream);
			// 对字节数组Base64编码
			BASE64Encoder encoder = new BASE64Encoder();
			//保存到redis
			Map temp = tokeService.createRandomToken(text);
			temp.put("img", encoder.encode(outputStream.toByteArray()));
			return ResultVO.success(temp);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultVO.error();
		}
	}
}
